import i18n from '@I18N'
import { date } from '@pier88health/p8h-common'
import { WEEKS_WORD_ENUM, WEEKS_ENUM } from '@CONSTANTS/consultation'
import { ScheduleTimesITF } from '@INTERFACES/Doctor'
import { MapLast7DaysITF, Last7DaysITF, ScheduleDateITF } from '@INTERFACES/Consultation'

export function getLast7Days(): Last7DaysITF[] {
  const oneDay = 1000 * 60 * 60 * 24
  const currDate = new Date().getTime()
  const recent = Array.from(Array(7)).map(
    (_, idx) => {
      const tempDay = new Date(currDate + oneDay * idx)
      const tempWeek = tempDay.getDay()
      const week = WEEKS_ENUM[tempWeek] as WEEKS_WORD_ENUM
      return ({
        Date: tempDay.getTime(),
        Day: tempDay.getDate(),
        Week: week,
        WeekNumber: tempWeek,
        FullTime: `${date.dateFormat(tempDay.getTime(), 'MM月dd日')} 周${i18n.weeks[week]?.()}`
      })
    }
  )
  return recent
}

export function transferLast7DaysToMap(data: ScheduleTimesITF[]): MapLast7DaysITF {
  const temp: MapLast7DaysITF = {}
  const oDate = new Date()
  const currHour = oDate.getHours()
  const currWeek = WEEKS_ENUM[oDate.getDay()]
  Array.isArray(data) && data.forEach(item => {
    const { Week, Times } = item

    // 筛选出小于当前时间的时间段
    let newTimes = []
    if (Week === currWeek) {
      try {
        newTimes = Times.filter(({ End }) => Number(End.split(':')[0]) > currHour)
      } catch (error) {
        newTimes = Times
      }
    } else {
      newTimes = Times
    }

    if (!temp[Week]) {
      temp[Week] = { ...item, Times: newTimes }
    }
  })
  return temp
}

export function getScheduleDateText(data: ScheduleDateITF): string {
  if (!data) return ''
  const {
    DateString, Start, End, Week
  } = data
  const currDay = date.dateFormat(new Date(DateString).getTime(), 'MM月dd日')
  const text = `${currDay} 周${i18n.weeks[Week]?.()} ${Start}-${End}`
  return text
}
